package CLI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Vector;

import start.Launch;
import IO.Read;
import IO.Save;

import web.Downloader;
import web.PopulateShow;
import data.Show;

public class CLI extends Thread 
{
	private Vector<Show> showList;
	public CLI(Vector<Show> showList, String version)
	{
		this.showList = showList;
		try {
			this.start(version);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void start(String version) throws IOException
	{
		System.out.println("Hello World, I am Sonny! "+ version);
		
		showList = Read.readShows();
		if(showList == null)
		{
			System.out.println("Sonny: You dont have any shows! Type \"add <SHOW NAME>\" to add a show");
			showList = new Vector<Show>();
		}

		
		InputStreamReader instream = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(instream);
		String nextInput;
		//Need Monitors or semaphores!
		while(true)
		{
			nextInput = in.readLine();
			if(nextInput.startsWith("add "))
			{
				System.out.println("Adding "+nextInput.split("add ")[1]);
				PopulateShow popShow = new PopulateShow(nextInput.split("add ")[1]);
				Show testShow1 = popShow.getShow();
				popShow = null;
				showList.add(testShow1);
				System.out.println("Added "+nextInput.split("add ")[1]);
			}
			else if(nextInput.startsWith("del "))
			{
				System.out.println("Removing "+nextInput.split("del ")[1]);
				for(int i=0; i<showList.size(); i++)
				{
					Show s = showList.get(i);
					if(s.getShowName().equals(nextInput.split("del ")[1]))
					{
						showList.remove(i);
						break;
					}
				}
			}
			else if(nextInput.startsWith("exit"))
			{
				this.shutdown();
			}
			else if(nextInput.startsWith("print "))
			{
				String toPrint = nextInput.split("print ")[1];
				if(toPrint.equals("showNames"))
				{
					for(Show s: showList)
					{
						System.out.println(s.getShowName());
					}
				}
				else
				{
					for(int i=0; i<showList.size(); i++)
					{
						Show s = showList.get(i);
						if(toPrint.equals("ALL") || s.getShowName().equals(toPrint))
						{
							System.out.println(s.toString());
							break;
						}
					}
				}
			}
			else if(nextInput.startsWith("populate quinns shows"))
			{
				LinkedList<String> quinnList = new LinkedList<String>();
				quinnList.add("Breaking Bad");
				quinnList.add("How I Met Your Mother");
				quinnList.add("Two and A Half Men");
				quinnList.add("The Big Bang Theory");
				quinnList.add("Dexter");
				quinnList.add("House");
				
				for(String show : quinnList)
				{
					System.out.println("Adding "+show);
					showList.add(new PopulateShow(show).getShow());
					System.out.println("Added "+show);
				}
				quinnList = null;
			}
			else if(nextInput.startsWith("download "))
			{
				for(int i=0; i<showList.size(); i++)
				{
					Show s = showList.get(i);
					System.out.println("Gonna download me sum " + nextInput.split("download ")[1]);
					
					if(s.getShowName().equals(nextInput.split("download ")[1]))
					{
						//testline because ezrss shit the bed when I made this downloader
						//s.getEpisodeToDownload().setTorrentURL("http://torrents.thepiratebay.org/6452796/inFAMOUS_2_OST_(Red_Version).6452796.TPB.torrent");
						new Downloader(s);
						
					}
				}
			}
			else if(nextInput.startsWith("select "))
			{	
				setSelectedEpisode(nextInput);
			}
//			else if(nextInput.startsWith("fb"))
//			{
//				heartbeatThread.interrupt();
//			}
			else if(nextInput.startsWith("nuke"))
			{
				showList.removeAllElements();
			}
			else
			{
				System.out.print(
				"Sonny: I dont understand ("+nextInput+"), but I do understand:\n"+
				"add <Show Name> : Add's a show to Sonny\n"+
				"del <Show Name> : Remove's a show from Sonny\n"+
				"print <Show Name> : Prints out the show name to console\n"+
				"printall : Prints out all shows names to console\n"+
				"select sXeY <ShowName> : Selects season X and episode Y as the pointer for the show\n"+
				"nuke : Destroys the saved shows\n"+
//				"fb : Forces the heartbeat awake\n"+
				"exit : Save's the currently running Sonny and then Sonny is brutally killed. Flowers will be at the funeral\n"
				);
			}
		}
	}
	private void shutdown()
	{
		try
		{
			Save.saveShows(Launch.showList);
		}
		catch(Exception e)
		{
			System.err.println("Error saving show!");
		}
		System.exit(0);
	}
	/*
	 * Selects the new episode 
	 */
	private void setSelectedEpisode(String nextInput) 
	{
		String[] selectArray = nextInput.split(" ");
		//[0] = select
		//[1] = sXeY
		//[2 - N] = Show
		if(selectArray.length < 2)
		{
			System.out.println("Select value is incorrect ("+nextInput+")\n");
			return;
		}
		
		int sIndex = selectArray[1].toLowerCase().indexOf("s");
		int eIndex = selectArray[1].toLowerCase().indexOf("e");
		
		int season = Integer.parseInt(selectArray[1].substring(sIndex+1, eIndex));
		int episode = Integer.parseInt(selectArray[1].substring(eIndex+1, selectArray[1].length()));
		
		String showName = "";
		for(int i =2; i<selectArray.length; i++)
		{
			showName += selectArray[i].toString()+" ";
		}
		showName = showName.trim();
		
		boolean foundShow = false;
		for(Show s : showList)
		{
			if(s.getShowName().equals(showName))
			{
				foundShow = true;
				if(s.getSeason(season).getEpisode(episode) != null)
				{
					s.setSelectedEpisode(season, episode);
				}
				else
				{
					System.out.println("Cannot find show @ s"+season+"e"+episode+"\n");
				}
			}
		}
		if(!foundShow)
		{
			System.out.println("Could not find show "+showName+"\n");
		}
		
	}
}
